package com.neisha.kit;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.neisha.job.HulfHourJob;
import com.neisha.job.OneDayJob;
import com.neisha.job.SendJob;
import com.neisha.job.TwoHourJob;

public final class JobKit {
	
	private static List<JobTrigger> triggers = new ArrayList<JobKit.JobTrigger>();
	private static Map<String,Integer> result = new HashMap<String, Integer>();
	
	private final static Logger logger = LoggerFactory.getLogger(JobKit.class);
	
	static{
		// 半小时执行一次的任务
		triggers.add(new JobTrigger("hulfhour","0 0/30 * * * ?",HulfHourJob.class));
		// 二小时执行一次的任务
		triggers.add(new JobTrigger("twohour","0 0 0/2 * * ?",TwoHourJob.class));
		// 一天执行一次的任务
		triggers.add(new JobTrigger("oneDay","0 0 12 * * ?",OneDayJob.class));
		
		// 一秒执行一次的任务 测试任务
		triggers.add(new JobTrigger("send","0/1 * * * * ?",SendJob.class));
	}
	
	
	public static List<JobTrigger> getTriggers(){
		return triggers;
	}
	
	public static Map<String,Integer> getResult(){
		return result;
	}
	
	public static String executeUrl(String url,String key){
		String res = "";
		try {
			String t = String.valueOf(new Date().getTime());
			String sign = MD5.md5((new Date().getTime())+Content.KEY);
			StringBuilder relUrl = new StringBuilder(url);
			relUrl.append("?t=").append(t)
			.append("&sign=").append(sign);
			res = HttpKit.get(relUrl.toString());
		} catch (Exception e) {
			res = "请求报错";
			logger.error("http is error,key:"+key,e);
		}
		count(key);
		return res;
	}
	
	public synchronized static void count(String key){
		Integer resCount = result.get(key);
		if(resCount == null){
			resCount = 0;
		}
		resCount += 1;
		result.put(key, resCount);
	}
	
	
	public static class JobResult{
		
		private String name;
		private int count = 0;
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getCount() {
			return count;
		}
		public void setCount(int count) {
			this.count = count;
		}
		
	}
	
	public static class JobTrigger{
		public JobTrigger(String name,String cron,Class<? extends Job> cls){
			this.name = name;
			this.cron = cron;
			this.cls = cls;
		}
		
		private String name;
		private String cron;
		private Class<? extends Job> cls;
		
		public String getName() {
			return name;
		}
		
		public String getCron() {
			return cron;
		}
		
		public Class<? extends Job> getCls() {
			return cls;
		}
		
	}
	
}
